//
//  LoginController.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 12/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift

extension String{
    func md5() ->String!{
        let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
        let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
        CC_MD5(str!, strLen, result)
        var hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.destroy()
        return String(format: hash as String)
    }
}

class LoginController: UIViewController, UIPickerViewDelegate, BMKLocationServiceDelegate {
    
    @IBOutlet weak var UserNameText: UITextField!
    @IBOutlet weak var UserPasswdText: UITextField!
    @IBOutlet weak var pickview: UIPickerView!

    let keychain = KeychainSwift(keyPrefix: "myTestKey_")
    let locService = BMKLocationService()
    var colors = ["京","津","沪","渝","冀","豫","云","辽","黑","湘","皖","鲁","新","苏","浙","赣","鄂","桂","甘","晋","蒙","陕","吉","闽","贵","粤","青","藏","川","宁","琼"]
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.pickview.delegate = self
        
        //设置LBS
        locService.delegate = self
        locService.desiredAccuracy = kCLLocationAccuracyBest
        locService.distanceFilter = 10
        
        locService.startUserLocationService()

        //self.SexPickView.delegate = self
    }
    
    //跳转首页
    @IBAction func changeFirst(sender: AnyObject) {
        //跳转到首页即可
        //self.dismissViewControllerAnimated(true, completion: nil)
        
        let secondStoryBoard = UIStoryboard.init(name: "Main", bundle: nil)
        
        let toLogin = secondStoryBoard.instantiateViewControllerWithIdentifier("FirstTabar")
        
        
        var window:UIWindow = UIApplication.sharedApplication().keyWindow!
        window.rootViewController = toLogin
        window.makeKeyAndVisible()
        
    }
    
    
    @IBAction func registerUser(sender: AnyObject) {
        print(UserNameText.text)
        print(UserPasswdText.text)
        let index    = pickview.selectedRowInComponent(0)
        let selected = colors[index]
        print(selected)
        
        //对密码进行md5加密
        let platNum = selected+UserNameText.text!
        //进行注册请求
        /*
        var parameters = [
            "plateNumber":platNum,
            "password":UserPasswdText.text!.md5(),
            "lng":keychain.get("registerlongitude")!,
            "lat":keychain.get("registerlatitude")!,
            "deviceType":"iphone",
            "sex":"男",
            "deviceCode":self.keychain.get("QCDTUUID")!
        ]*/
        var parameters = [
            "plateNumber":platNum,
            "password":UserPasswdText.text!.md5(),
            "lng":keychain.get("registerlongitude")!,
            "lat":keychain.get("registerlatitude")!,
            "deviceType":"iphone",
            "deviceCode":self.keychain.get("QCDTUUID")!
        ]
        
        Alamofire.request(.POST, "http://42.62.18.210:8090/apiradio/ar/manualLogin", parameters:parameters).responseJSON { response in
            if let result = response.result.value {
                print("JSON: \(result)")
                let json = JSON(result)
                if String(json["msg"]) == "200" {
                    //1.增加用户ID和更新用户的topic
                    self.keychain.set(String(json["obj"]["userID"]), forKey: "registerUserID")
                    self.keychain.set(String(json["obj"]["personTopic"]), forKey: "personTopic")
                    
                    self.keychain.set(platNum, forKey: "QCDTUSERNAME")
                    self.keychain.set(self.UserPasswdText.text!.md5(), forKey: "QCDTUSEPASSWD")
                
                    
                    //2.停止取坐标
                    self.locService.stopUserLocationService()
                    
                    //3.跳转到好友列表页
                    let secondStoryBoard = UIStoryboard.init(name: "Main", bundle: nil)
                    
                    let toLogin = secondStoryBoard.instantiateViewControllerWithIdentifier("FirstTabar")
                    
                    
                    var window:UIWindow = UIApplication.sharedApplication().keyWindow!
                    window.rootViewController = toLogin
                    window.makeKeyAndVisible()
                    
                }
                

            }
        }
        
        //进行尝试登录, 如果登陆成功则
    }
    
    func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) {
        print("--------------")
        print("\(userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude)")
        let test1 = userLocation.location.coordinate.latitude
        let test2 = userLocation.location.coordinate.longitude
        
        //对坐标进行存储,并且关闭
        //设置
        self.keychain.set(String(test1), forKey: "registerlatitude")
        self.keychain.set(String(test2), forKey: "registerlongitude")
        
        //self.locService.stopUserLocationService()
    }
    
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int)->Int {
        return colors.count
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return colors[row]
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        UserNameText.resignFirstResponder()
        UserPasswdText.resignFirstResponder()
    }
}